{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "e4f5bf9e-d03e-4159-bee9-fda8926b5a36",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import os\n",
    "import torch.nn as nn\n",
    "import torch.optim as optim\n",
    "from torch.utils.data import DataLoader\n",
    "from torchvision import datasets, transforms\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "# 指定日志目录\n",
    "log_dir = \"logs/experiment_1\"\n",
    "writer = SummaryWriter(log_dir=log_dir)\n",
    "# 数据加载与预处理\n",
    "transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])\n",
    "mnis_dir=os.getenv('HOME')+\"/SUFE/mnist\"\n",
    "trainset = datasets.MNIST(root=mnis_dir, train=True, download=True, transform=transform)\n",
    "trainloader = DataLoader(trainset, batch_size=32, shuffle=True)\n",
    "x = torch.arange(-5, 5, 0.1).view(-1, 1)\n",
    "y = -5 * x + 0.1 * torch.randn(x.size())\n",
    "\n",
    "model = torch.nn.Linear(1, 1)\n",
    "criterion = torch.nn.MSELoss()\n",
    "optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)\n",
    "\n",
    "def train_model(iter):\n",
    "    for epoch in range(iter):\n",
    "        y1 = model(x)\n",
    "        loss = criterion(y1, y)\n",
    "        writer.add_scalar(\"Loss/train\", loss, epoch)\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "\n",
    "train_model(10)\n",
    "writer.flush()\n",
    "writer.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5e88e4d8-f701-4b30-81d2-db5a90d9f8a1",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
